<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\ArticleModel;
use app\admin\model\ProductModel;
use app\admin\model\ProductTripModel;
use app\admin\model\ProductCostModel;

class Articles extends Base
{
    // 文章列表
    public function index()
    {
        if(request()->isAjax()){
            $param = input('param.');

            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                $where['title'] = ['like', '%' . $param['searchText'] . '%'];
            }
            $article = new ProductModel();
            $selectResult = $article->getArticlesByWhere($where, $offset, $limit);

            foreach($selectResult as $key=>$vo){
                switch ($vo['type'])
                {
                    case 1:
                        $selectResult[$key]['type'] = '自由行';
                        break;
                    case 2:
                        $selectResult[$key]['type'] = '海口出行';
                        break;
                    case 3:
                        $selectResult[$key]['type'] = '三亚出行';
                        break;
                    default:
                }
                switch ($vo['status'])
                {
                    case 1:
                        $selectResult[$key]['status'] = '<span>上架</span>';
                        break;
                    case 2:
                        $selectResult[$key]['status'] = '<span style="color: red">下架</span>';
                        break;
                    default:
                }
                $selectResult[$key]['images'] = '<img src="' . $vo['images'] . '" width="40px" height="40px">';
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id'], $vo['status']));
            }
            $return['total'] = $article->getAllArticles($where);  // 总数据
            $return['rows'] = $selectResult;
//            echo "<pre>";
//            print_r($return);
//            echo "</pre>";
//            exit();
            return json($return);
        }

        return $this->fetch();
    }

    // 添加产品
    public function articleAdd()
    {
        if(request()->isPost()){
            $param = input('post.');

            $param['add_time'] = date('Y-m-d H:i:s');
            preg_match_all('/<img[^>]*?src="([^"]*?)"[^>]*?>/i',$param['info'],$match);
            $param['info'] = implode(',', $match[1]);
            $product = new ProductModel();
            $flag = $product->addArticle($param);
            $this->success('产品信息添加成功','/admin/articles/tripadd?id='.$flag['data'] , '' , 1);
        }

        return $this->fetch();
    }

    /*
     *  添加跟团行程
     */
    public function tripAdd()
    {
        $pid = input('get.id');
        $ProductTrip = new ProductTripModel();
        if(request()->isPost()){
            $param = input('post.');
            $result = $ProductTrip->addProductTrip($param);
            if ($result['code']) {
                $this->success('行程添加成功','/admin/articles/tripadd?id='.$param['p_id'], '' , 1);
            }
        }
        $data = $ProductTrip->where('p_id', '=', $pid)->select();
        $this->assign('pid', $pid);
        $this->assign('data', $data);
        return $this->fetch();
    }

    /*
     *  跟团行程编辑
     */
    public function tripEdit()
    {
        $article = new ProductTripModel();
        if(request()->isPost()){
            $param = input('post.');
            $flag = $article->editTrip($param);
            $this->success('行程编辑成功','/admin/articles/tripadd?id='.$flag['data'], '' , 1);
        }
        $p_id = input('param.p_id');
        $getAll = $article->getAllProduct($p_id);
        if (!$getAll) {
            $url = '/admin/articles/tripadd?id='.$p_id;
            $this->redirect($url);
        }
        $this->assign('pid', $p_id);
        $this->assign([
            'data' => $getAll
        ]);
        return $this->fetch();
    }

    /*
     *  添加旅游费用
     */
    public function costAdd($pid)
    {
        $productCost = new ProductCostModel();
        if(request()->isPost()){
            $param = input('post.');
            $param['p_id'] = $pid;
            $result = $productCost->addProductCost($param);
            if ($result['code']) {
                $this->success('费用添加成功','/admin/articles/index' , '' , 1);
            }
        }
        $this->assign('pid', $pid);

        return $this->fetch();
    }

    /*
     *  产品费用编辑
     */
    public function costEdit()
    {
        $article = new ProductCostModel();
        if(request()->isPost()){
            $param = input('post.');

            $flag = $article->editCost($param);
            $this->success('操作成功','/admin/articles/costedit?p_id='.$param['p_id'], '' , 1);
        }
        $p_id = input('param.p_id');

        $getOneInfo = $article->getOneCost($p_id);

        $this->assign('pid', $p_id);
        $this->assign([
            'data' => $getOneInfo
        ]);
        return $this->fetch();
    }


    public function articleEdit()
    {
        $article = new ProductModel();
        if(request()->isPost()){
            $param = input('post.');
            unset($param['file']);
            preg_match_all('/<img[^>]*?src="([^"]*?)"[^>]*?>/i',$param['info'],$match);
            $param['info'] = implode(',', $match[1]);

            $flag = $article->editArticle($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        }

        $id = input('param.id');

        $getInfo = showEdirtImg($article->getOneArticle($id));

        $this->assign([
            'article' => $getInfo
        ]);
        return $this->fetch();
    }
    //上下架
    public function articleDel()
    {
        $id = input('param.id');

        $article = new ProductModel();
        $flag = $article->delArticle($id);
        return json(msg($flag['code'], $flag['data'], $flag['msg']));
    }

    // 上传缩略图
    public function uploadImg()
    {
        if(request()->isAjax()){

            $file = request()->file('file');
            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload');
            if($info){
                $src =  '/upload' . '/' . date('Ymd') . '/' . $info->getFilename();
                return json(msg(0, ['src' => $src], ''));
            }else{
                // 上传失败获取错误信息
                return json(msg(-1, '', $file->getError()));
            }
        }
    }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id)
    {
        return [
            '产品编辑' => [
                'auth' => 'articles/articleedit',
                'href' => url('articles/articleedit', ['id' => $id]),
                'btnStyle' => 'primary',
                'icon' => 'fa fa-paste'
            ],
            '行程编辑' => [
                'auth' => 'articles/articleedit',
                'href' => url('articles/tripedit', ['p_id' => $id]),
                'btnStyle' => 'info',
                'icon' => 'fa fa-paste'
            ],
            '费用编辑' => [
                'auth' => 'articles/articleedit',
                'href' => url('articles/costedit', ['p_id' => $id]),
                'btnStyle' => 'info',
                'icon' => 'fa fa-paste'
            ],
            '上下架' => [
                'auth' => 'articles/articledel',
                'href' => "javascript:articleDel(" . $id .")",
                'btnStyle' => 'danger',
                'icon' => 'fa fa-trash-o'
            ]
        ];
    }
}
